var express = require('express');
var router = express.Router();
const {exec} = require('../db/mysql.js');
const {getList,getDetail,del,newBlog,updateBlog} = require('../controller/blog.js');
const loginCheck = require('../middleware/loginCheck.js');
router.get('/list', function(req, res, next) {
	const author = req.query.author || "";
	const keyword = req.query.keyword || "";
	getList(author,keyword).then(e=>{
		res.json({
			errno:0,
			data:e
		});
	});
  
});
router.get('/detail',(req,res,next) => {
	const id = req.query.id || "";
	getDetail(id,res).then(e=>{
		res.json({
			errno:0,
			data:e
		});
	});
});

router.post('/del',loginCheck,(req,res,next) => {
	const id = req.body.id || "";
	del(id,res).then(e=>{
		if(e.affectedRows != 0){
			res.json({
				errno:0,
				data:'Succ'
			});
		}else{
			res.json({
				errno:-1,
				data:'Err'
			});
		}
		
	});
});

router.post('/newBlog',loginCheck,(req,res,next) => {
	let newBlogDate = req.body;
	newBlogDate.author = req.session.username;
	newBlog(newBlogDate).then(e=>{
		if(e.affectedRows != 0 ){
			res.json({
				errno:0,
				data:'新建成功'
			});
		}else{
			res.json({
				errno:0,
				data:'新建失败'
			});
		}
		
	});
});
router.post('/update',loginCheck,(req,res,next) =>{
	let id = req.body.id;
	let update = req.body;
	updateBlog(id,update).then(e=>{
		if(e.affectedRows!=0){
			res.json({
				errno:0,
				data:"修改成功"
			});
		}else{
			res.json({
				errno:0,
				data:'修改失败'
			});
		}
	});
});

module.exports = router;
